package com.example.shiyun.Util;

import android.util.Log;

import com.example.shiyun.Pojo.Pojo_Sentence;
import com.example.shiyun.Pojo.Pojo_SentenceData;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * okhttp获取数据
 */
public class Util_Okhttp {
    //天气数据
    public static void ok_get(String url)
    {
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder()
                .url("http://t.weather.itboy.net/api/weather/city/"+url)
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("xx","解析出错");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                EventBus.getDefault().post(response.body().string());
                Log.d("xx","解析成功");
            }
        });
    }
    //每日一句数据
    public static void ok_get_Sentence()
    {
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder()
                .url("http://open.iciba.com/dsapi/")
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("xx","解析出错");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                //删除所有数据
                LitePal.deleteAll(Pojo_SentenceData.class);
                //gson解析
                Gson gson=new Gson();
                Pojo_Sentence pojo_sentence = gson.fromJson(str, Pojo_Sentence.class);
                Pojo_SentenceData pojoSentenceData=new Pojo_SentenceData();
                //设置数据
                pojoSentenceData.setNote( pojo_sentence.getNote());
                pojoSentenceData.save();
            }
        });


    }
}
